/*
 * create:2016年1月7日 下午11:18:26
 * author:wangds  
 */

package net.wangds.common.command.test;

import junit.framework.TestCase;

import net.wangds.common.command.AbstractTextCommand;
import net.wangds.common.command.CommandClient;
import net.wangds.common.command.CommandReceiver;
import net.wangds.common.command.DefaultCommandInvoker;
import net.wangds.common.command.Invoker;

import org.junit.Test;

import java.util.Stack;

/**
 * .
 * 
 * @author wangds
 *
 */
public class CommandTestCase {

  @Test
  public void test() throws Exception {

    String[] texts = new String[] { "1", "2", "3" };

    Client client = new ClientImpl();
    for (String cur : texts) {
      client.executeCommand(cur);
    }

    Stack<String> his = TestCommandReceiver.HISTORY;
    TestCase.assertEquals(his.size(), texts.length);
    while (!his.isEmpty()) {
      TestCase.assertEquals(his.pop(), texts[his.size()]);
    }
  }

}

interface Client {
  void executeCommand(String text) throws Exception;
}

class ClientImpl implements CommandClient<TestCommandReceiver>, Client {

  private TestCommandReceiver receiver = new TestCommandReceiver();
  private Invoker<TestCommandReceiver, TestTextCommand> commandInvoker = new DefaultCommandInvoker<>();

  private String commandText = "";

  public void setCommandText(String text) {
    this.commandText = text;
  }

  /*
   * @see net.wangds.common.command.CommandClient#newCommand()
   * 
   * @author wangds 2016年1月7日 下午11:19:21.
   */
  @Override
  public TestTextCommand newCommand() {
    return new TestTextCommand(this.commandText);
  }

  public void executeCommand(String text) throws Exception {
    this.setCommandText(text);
    TestTextCommand cmd = commandInvoker.buildCommand(receiver, this.newCommand());
    commandInvoker.invoke(cmd);
  }

}

class TestTextCommand extends AbstractTextCommand<TestCommandReceiver> {

  public TestTextCommand(String cmd) {
    this.setCommandText(cmd);
  }

  /*
   * @see net.wangds.common.processor.Processor#process()
   * 
   * @author wangds 2016年1月7日 下午11:20:48.
   */
  @Override
  public void process() throws Exception {
    TestCommandReceiver r = this.getReceiver();
    r.onReceiveCommand(this);
  }

}

class TestCommandReceiver implements CommandReceiver {

  public static Stack<String> HISTORY = new Stack<String>();

  public void onReceiveCommand(TestTextCommand cmd) {
    HISTORY.push(cmd.getCommandText());
  }

}
